import { JXDef } from "../../../conventions/JXCommon";
import GParam from "../../../Core/GEvent/GParam";
import GChild from "../../../Core/GView/GChild";
import { AudioMgr } from "../../../Core/Manager/AudioMgr";
import { JXLocales } from "../../Common/Zh";
import GameMgr from "../../Logic/GameMgr";
import JXBtlMgr from "../JXBattle/JXBattleManager";
import JXRBCmdMgr from "../JXBattle/JXRBCmdMgr";
import { GCtrl } from './../../../Core/GCtrl';
import { CMsg, GRID_TYPE, INFO_TYPE } from './../../Common/Define';
import { Res } from './../../Common/UIResources';
import { JXBtlCamp } from './../JXBattle/JXBattleDefine';

const { ccclass, property, menu } = cc._decorator;
@ccclass @menu("View/Fight/BtlHeroHead")
export default class BtlHeroHead extends GChild {
	@property(cc.Sprite) head: cc.Sprite = null;
	@property(cc.Label) need: cc.Label = null;
	@property(cc.Sprite) bg: cc.Sprite = null;
	@property(cc.Label) type: cc.Label = null;
	@property(cc.Sprite) mask: cc.Sprite = null;


	private _rHeroData: IHeroBtlData = null;
	private _sHeroData: SHeroDataRaw = null;

	protected _touchMove: boolean = false;
	protected _iconShowNode: cc.Node = null;
	protected _touchBegin: boolean = false;
	protected _dragShowNode: cc.Node = null;
	protected _isDraging: boolean = false;
	private _canDraw: boolean = false;
	private _seatNode: cc.Node = null;
	protected _onSeat: boolean = false;
	private _time: number = 0;
	private _chess = [null, '兵', '车', '马', '炮', "相", "士"];

	public onGLoad(): void {
		GCtrl.ES.on(GCtrl.GTimerSecondEventMsg, this, this.setMaskRank.bind(this))
	}

	/**暂存的点 */
	private _curPos: cc.Vec2 = null;
	private _cmd: JXRBCmdMgr = null;

	public init(hero: IHeroBtlData, cmd: JXRBCmdMgr) {
		this.node.name = "btlHead_" + hero.tableId;
		this._cmd = cmd;
		this._rHeroData = hero;
		this._sHeroData = GameMgr.heroData.getRaw<SHeroDataRaw>(hero.tableId);
		this.setView();
	}

	protected setMaskRank() {
		let config = GameMgr.systemConfig.value<number>(JXDef.SYS_CONFIG_KEY.twoUp) * this._time;
		let expend = Math.round(this._sHeroData.food * (1 + config));
		let progress = this._cmd.wheat / expend;
		if (progress > 1) {
			cc.tween(this.mask).to(0.5, { fillRange: 1 }).start();
			this.mask.node.active = false;
		} else {
			this.mask.node.active = true;
			cc.tween(this.mask).to(0.5, { fillRange: (1 - progress) }).start();
		}
	}

	protected setView() {
		this.updateExpend();
		this.assetImpl.spriteAtlasFrame(this.bg, Res.texture.fight.ui, "trait_" + this._rHeroData.trait)
		this.assetImpl.spriteFrame(this.head, Res.texture.hero.hero + "hero_" + this._sHeroData.icon);
		this.type.string = this._chess[this._sHeroData.type] + '';
	}

	public initEvent() {
		this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchStar, this);
		this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
		this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnd, this);
		this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancel, this);
	}

	public checkStatus() {
		if (!this._sHeroData) {
			this._canDraw = false;
		} else {
			this._canDraw = true;
		}
	}

	public setSeatNode(node: cc.Node) {
		this._seatNode = node;
	}

	public destroyDragNode() {
		if (cc.isValid(this._dragShowNode)) {
			this._dragShowNode.destroy();
			this._dragShowNode = null;
		}
	}

	private _onTouchStar(event: cc.Event.EventTouch) {
		let config = GameMgr.systemConfig.value<number>(JXDef.SYS_CONFIG_KEY.twoUp) * this._time;
		let expend = Math.round(this._sHeroData.food * (1 + config))
		let isEnough = this._cmd.wheat >= expend
		if (!isEnough) {
			this._canDraw = false;
			GameMgr.uiMgr.showToast(JXLocales.fight.noWheat);
			return;
		}
		this.checkStatus();
		this._touchMove = false;
		this.destroyDragNode();
		this._touchBegin = true;
		event.stopPropagation();
	}

	private _onTouchMove(event: cc.Event.EventTouch) {
		if (!this._canDraw) {
			return;
		}
		let deltaMove = event.getLocation().sub(event.getStartLocation());
		if (!this._isDraging) {
			this._isDraging = true;
		}
		if (deltaMove.mag() > 7 && this._isDraging) {
			let parent = this._seatNode;
			if (!this._touchMove) {
				this._touchMove = true;
				this._dragShowNode = cc.instantiate(this.head.node);
				this._dragShowNode.parent = this._seatNode;
				let localPos: cc.Vec2 = parent.convertToNodeSpaceAR(event.getLocation());
				this._dragShowNode.setPosition(localPos);
			} else {
				let worldPos = event.getLocation();
				let localPos: cc.Vec2 = parent.convertToNodeSpaceAR(worldPos);
				this._dragShowNode.setPosition(localPos);
				let result = this._seatNode.getBoundingBoxToWorld().contains(worldPos);
				let activePos = this._cmd.btlMapConverts.converToMapPos(localPos);
				if (!this._curPos || activePos.x != this._curPos.x || activePos.y != this._curPos.y) {
					let info: SelectGridInfo = {
						heroId: this._sHeroData.id,
						pos: activePos
					}
					GCtrl.ES.emit(CMsg.client.fight_ui.selectItem, new GParam(info))
					this._curPos = activePos;
				}
				if (result) {
					if (!this._onSeat) {
						this._onSeat = true;
					}
				} else {
					if (this._onSeat) {
						this._onSeat = false;
					}
				}
			}
		}
	}

	public _onTouchEnd(event: cc.Event.EventTouch, isCancel = false) {
		let worldPos = event.getLocation();
		this.destroyDragNode();
		if (this._touchMove) {
			let result = this._seatNode.getBoundingBoxToWorld().contains(worldPos)
			let localPos: cc.Vec2 = this._seatNode.convertToNodeSpaceAR(worldPos);
			let activePos = this._cmd.btlMapConverts.converToMapPos(localPos);
			if (result) {
				this.putOnHeroInBtl(activePos);
			}
			GCtrl.ES.emit(CMsg.client.fight_ui.hideAllItem);
		} else {
			if (isCancel == false) {
			}
		}
		this._touchBegin = false;
		this._touchMove = false;
		this._onSeat = false;
		this._isDraging = false;
	}

	protected updateExpend() {
		let config = GameMgr.systemConfig.value<number>(JXDef.SYS_CONFIG_KEY.twoUp) * this._time;
		let expend = Math.round(this._sHeroData.food * (1 + config));
		this.need.string = expend.toString();
	}

	/**英雄*/
	public putOnHeroInBtl(pos: cc.Vec2) {
		let config = GameMgr.systemConfig.value<number>(JXDef.SYS_CONFIG_KEY.twoUp) * this._time;
		let expend = Math.round(this._sHeroData.food * (1 + config))
		let isPutOn = this._cmd.checkCanPutOn(JXBtlCamp.Defenser, pos);
		let isEnough = this._cmd.wheat >= expend
		let isPlace = this._cmd.btlCameraMap.selectGridByPos(pos).data.gridInfo[INFO_TYPE.GRID] === GRID_TYPE.PLACE
		if (!isPutOn && isPlace) {
			if (isEnough) {
				let hero = JXBtlMgr.ins.getTeamByCamp(JXBtlCamp.Defenser).goBattle(this._rHeroData.heroId)
				// GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.battle, { msg: this._sHeroData.name + "上阵" });
				this._cmd.jxBtlAns.setDefToTeam(hero);
				this._cmd.createRole(hero.heroId, hero.index, JXBtlCamp.Defenser, null, pos);
				AudioMgr.Ins().playEffect(Res.audio.goBattle);
				this._cmd.expendWheat(expend);
				this._time++;
				this.updateExpend();
			} else {
				GameMgr.uiMgr.showToast(JXLocales.fight.noWheat)
			}
		} else {
			GameMgr.uiMgr.showToast(JXLocales.fight.hasHero)
		}
	}

	/**触摸取消 */
	private _onTouchCancel(event: cc.Event.EventTouch) {
		// let isGuide1 = GameMgr.lUserData.isGuidseExits()
		// let isGuide2 = GameMgr.lUserData.isGuidseExits()
		// let isGuide3 = GameMgr.lUserData.isGuidseExits()
		// if (!isGuide1 || !isGuide2 || !isGuide3) {
		// 	this._touchBegin = false;
		// 	this._touchMove = false;
		// 	this._onSeat = false;
		// 	this._isDraging = false;
		// 	this.destroyDragNode();
		// 	GCtrl.ES.emit(CMsg.client.fight_ui.hideAllItem);
		// } else {
		this._onTouchEnd(event, true)
		// }

	}

	public onEnable() {
		this.initEvent();
	}

	public onDisable() {
		this.node.targetOff(this);
	}


}